
#include "VideoRecorder.hpp"
#include <boost/filesystem.hpp>
namespace Moduels::FramesIO
{

    void VideoRecorder::Init()
    {
        int video_format=Format.VideoFormat;
        double fps=Format.Fps;

        VideoPath= CreateFilePath(VideoPath);

        Save2New();
    }

    std::string VideoRecorder::CreateFilePath(std::string path)
    {
        int index=0;
        if(!boost::filesystem::exists(path))
        {
            if (!boost::filesystem::create_directories(path))
            {
                std::cout << "Create Video Path:" << path << " Failed" << std::endl;
            }
        }
        for(auto iterator=begin(boost::filesystem::directory_iterator(path));
                    iterator!=end(boost::filesystem::directory_iterator(path));iterator++)
        {
            if(is_directory((*iterator)))
            {
                index++;
//                std::cout<<(*iterator).path().filename()<<std::endl;
            }
            else
            {

            }
        }
        index++;
        path=path+"/"+std::to_string(index);
        if(!boost::filesystem::exists(path))
        {
            if (!boost::filesystem::create_directories(path))
            {
                std::cout << "Create Video Path:" << path << " Failed" << std::endl;
            }
        }
        return path;
    }

    void VideoRecorder::AddFrameToVideo(cv::Mat frame)
    {
        VideoBuilder << frame;
        auto now=std::chrono::steady_clock::now();
        auto duration=std::chrono::duration_cast<std::chrono::seconds>(now-LastTime).count();
        if(duration>300)
        {
           Save2New();
        }
    }

    void VideoRecorder::Save2New()
    {
        Index++;
        VideoBuilder.open(  VideoPath+'/'+std::to_string(Index)+Format.VideoSuffix,
                            Format.VideoFormat,
                            Format.Fps,
                            VideoSize,
                            true);
        if(!VideoBuilder.isOpened())
        {
            std::cout<<"Video Builder Open Failed"<<std::endl;
        }
        LastTime=std::chrono::steady_clock::now();
    }
}